/*
 * @Descripttion:
 * @version: 1.0.0
 * @Author: Shentong
 * @Date: 2021-04-09 12:34:34
 * @LastEditors: Shentong
 * @LastEditTime: 2021-11-08 22:40:54
 */
import React, { useEffect, useMemo, useState, useReducer, useCallback } from "react";
import { View,Text,Image } from "@tarojs/components";
import Taro, { useReachBottom, useDidShow, usePullDownRefresh } from "@tarojs/taro";

import { AtAvatar, AtIcon, AtCurtain } from 'taro-ui'

import { DefaultAvatar, orderStauts } from '@/src/constants/data'

import { getOrderList, getEatQrcode } from '@/api/order'

import NoMore from "@/components/custom/no-more";

import NoDataIcon from '@/src/assets/icon/noDataIcon.png'

import Comment from './components/comment/index'

import QrcodeCurtain from "@/src/components/custom/qrcodeCurtain";


import styles from './index.module.scss'

const listReducer = (state, action) => {
  switch (action.type) {
    case 'init': return action.payload
    case 'concat': return state.concat(action.payload)
    default: return state
  }
}


function Order() {
  const [currentTab, setCurrentTab] = useState(0);
  const [showComment, setShowComment] = useState<boolean>(false)

  // 星星、包装、口味
  const [starCount, setStarCount] = useState<number>(5)
  const [statisfyCount, setStatisfyCount] = useState<number>(5)
  const [flavorCount, setFlavorCount] = useState<number>(5)
  const [isLoadFinish, setIsLoadFinish] = useState(false)
  const [orderList, localDispatch] = useReducer(listReducer, [])
  const [reqParams, setReqParams] = useState({ pageNo: 1, queryType: 0, pageSize: 20 })

  // 当期选中需要评价的某一订单item
  const [curOrderItem, setCurOrderItem] = useState({})

  // 查看二维码
  const [showQrModel, setShowQrModel] = useState<boolean>(false)
  const [qrcodeImg, setQrCodeImg] = useState<string>('')


  const tabList = useMemo(()=> {
    return [{ title: '全部订单', queryType: 0 }, { title: '待评价', queryType: 1 }, { title: '退款', queryType: 2 }]
  }, [])

  const getOrderPage = useCallback(() => {
    Taro.showLoading({ title: "加载中...", mask: true })

     getOrderList(reqParams).then(res=> {
       const { data: { records = [], lastPage = false } = {} } = res

       records.forEach(item => {
         const { goods = [] } = item
         item.allGoodsCount = goods.reduce(function(prev, { goodsNum = 0 }) {
          return goodsNum + prev
        }, 0)
       })

      setIsLoadFinish(lastPage)

       const actionType = reqParams.pageNo === 1 ? 'init' : 'concat'
      localDispatch({ type: actionType, payload: records })

      Taro.hideLoading();
     }).finally(() => {
       Taro.stopPullDownRefresh();
     })
  },[reqParams])




  const tabClickHandle = (tab, index) => {
    setCurrentTab(index)

    setReqParams({
      ...reqParams,
      queryType: index,
      pageNo: 1
    })
  }

  const goOrderDetail = ({ orderSId }) => {
    Taro.navigateTo({
      url: `/pages/orderDetail/index?orderId=${orderSId}`
    })
  }

  const commentCloseHandle = () => {
    setShowComment(false)
    setStatisfyCount(5)
    setFlavorCount(5)
    setStarCount(5)
    setCurOrderItem({})
  }

  // 保存成功
  const saveSuccessHandle  =() => {
    commentCloseHandle()
    // 刷新页面
    Taro.startPullDownRefresh()
  }

  // 去评价
  const goComment = (e, item) => {
    e.stopPropagation()
    setCurOrderItem({ ...item })

    setShowComment(true)
  }

  const qrcodeOnClose = () => {
    setShowQrModel(false)
  }

  // 再来一单
  const onceAgain = (e, { shopSId }) => {
    e.stopPropagation()
    Taro.navigateTo({
      url: `/pages/detail/index?shopId=${shopSId}`
    })
  }

  const getQrcode = (e, { code = '' }) => {
    e.stopPropagation()

    if (code ){
      var imgData = code.replace(/[\r\n]/g, '') // 将回车换行换为空字符''
      setShowQrModel(true)
      setQrCodeImg(imgData)
    }
  }

  // 刷新
  const doRefresh = () => {
    if (reqParams.pageNo !== 1) {
      setReqParams({
        ...reqParams,
        pageNo: 1
      })
    } else {
      getOrderPage()
    }
  }

  useEffect(() => {
    getOrderPage()
  }, [getOrderPage]);

  useDidShow(() => {
    doRefresh()
  })

  // 触底加载
  useReachBottom(() => {
    if (!isLoadFinish) {
      setReqParams({
        ...reqParams,
        pageNo: reqParams.pageNo + 1
      })
    }
  })

  // 下拉刷新
  usePullDownRefresh(() => {
    doRefresh()
  });

  /**
   * @description vant组件，无法作用到子组件中，以chlder形式传入下去 START
  */
  const statisfyChange = ({ detail }) =>{
    setStatisfyCount(detail)
  }

  const flavorChange = ({ detail }) =>{
    setFlavorCount(detail)
  }

  const starComps = <van-rate value={starCount} voidIcon='star-o' icon='star' size={26} onChange={(e) => setStarCount(e.detail)} />
  const flavorComps = <van-rate value={flavorCount} icon='smile' size={26} voidIcon='smile-o' onChange={flavorChange} />
  const statisfyComps = <van-rate value={statisfyCount} voidIcon='smile-o' icon='smile' size={26} onChange={statisfyChange} />

  /**
   * @description vant组件，无法作用到子组件中，以chlder形式传入下去 END
  */

  return (
    <View className={styles.order}>
      <View className={styles.headerTabs}>
        {
          tabList.map((tab, index) => {
            return (<View
              className={`${styles.tab} ${currentTab === index ? styles.active : null}`}
              key={`tab_${index}`}
              onClick={() => tabClickHandle(tab, index)}
            >{tab.title}</View>)
          })
        }

      </View>
      <View className={styles.orderListContainer}>
        {
          orderList.map((orderItem, index) => {
            return (
              <View className={styles.item} key={`orderItem_${index}`}  onClick={() => goOrderDetail(orderItem)}>
                <AtAvatar image={orderItem.shopImageUrl || DefaultAvatar} className={styles.headerImg} size='small'></AtAvatar>
                <View className={styles.rtTtx}>
                  <View className={styles.header}>
                      <View className={styles.title}>
                        <View className={styles.name}>{orderItem.shopName}</View>
                        <AtIcon value='chevron-right' size='18' color='#666'></AtIcon>
                      </View>
                      <View className={styles.status}>{orderStauts[orderItem.orderStatus]}</View>
                  </View>
                  <View className={styles.content}>
                      <View className={styles.goods}>
                        <View className={styles.ctx}>
                          <View className={styles.prodName}>{orderItem.goods && orderItem.goods.length ? orderItem.goods[0].goodsName : ''}...</View>
                          <View className={styles.count}>共{orderItem.allGoodsCount}件商品</View>
                        </View>
                        {
                          orderItem.eatCode ? (
                              <View className={styles.orderSeq}>
                                取餐码：<Text className={styles.txt}>{orderItem.eatCode}</Text>
                              </View>
                          ) : null
                        }

                      </View>
                      <View className={styles.goods} style={{justifyContent: "flex-end"}}>
                        {
                          orderItem.orderSeq ? (
                              <View className={styles.orderSeq}>
                                序号：<Text className={`${styles.txt} ${styles.orderIndex}`}>{orderItem.orderSeq}</Text>
                              </View>
                          ) : null
                        }
                      </View>
                      {
                        orderItem.eatAddress ? (
                          <View className={styles.eatAddressInfo}>
                            <View className={styles.eatAddress}>
                              取餐地址：<Text className={styles.txt}>{orderItem.eatAddress}</Text>
                            </View>
                            <View className={styles.eatQrCode} onClick={(e) => getQrcode(e, orderItem)}>查看二维码</View>
                          </View>
                        ) : null
                      }

                      <View className={styles.price}>共计￥{orderItem.amount}</View>
                  </View>
                  <View className={styles.btn}>
                    { orderItem.orderStatus === 4 && orderItem.evaluateStatus === 0 ? <View className={styles.aBtn} onClick={(e)=> goComment(e, orderItem)}>评价</View> : null}


                    <View className={styles.aBtn} onClick={(e) => onceAgain(e, orderItem)}>再来一单</View>
                  </View>
                </View>
              </View>
            )
          })
        }
        {orderList.length && isLoadFinish ? <NoMore /> : null}
      </View>
      {/* 查看二维码弹出框 */}
      <QrcodeCurtain showModel={showQrModel} image={qrcodeImg} onCloseHandle={qrcodeOnClose} />
      {/* 暂无数据 */}
      {
         isLoadFinish && !orderList.length && (
          <van-empty description='暂无数据' image={NoDataIcon} />
         )
      }

       <View className={styles.layoutBox}  catchMove >
          <Comment
            showComment={showComment}
            handleClose={commentCloseHandle}
            saveSuccess={saveSuccessHandle}
            starComps={starComps}
            flavorComps={flavorComps}
            statisfyComps={statisfyComps}
            starCount={starCount}
            flavorCount={flavorCount}
            statisfyCount={statisfyCount}
            commentItem={curOrderItem}
          />
       </View>
    </View>
  );
}

export default Order
